<template>
  <div class="mapWrapper">
    <div class="mapContainer" id="mapContainer"></div>
  </div>
</template>

<script setup>
import AMapLoader from '@amap/amap-jsapi-loader'
import { ref, onMounted, onBeforeUnmount } from 'vue'
import { district } from './district'
import { points } from './community'

import { elRectification } from 'autofit.js'

console.log(district)
console.log(points)

var count = points.length
function clusterMarkers() {
  var markerList = []
  var marker = new AMap.Marker({
    map: map
  })
  markerList.push(marker)
  return markerList
}

var clusterIndexSet = {
  city: {
    minZoom: 2,
    maxZoom: 10
  },
  district: {
    minZoom: 10,
    maxZoom: 12
  },
  area: {
    minZoom: 12,
    maxZoom: 15
  },
  community: {
    minZoom: 15,
    maxZoom: 22
  }
}
function getStyle(context) {
  var clusterData = context.clusterData // 聚合中包含数据
  var index = context.index // 聚合的条件
  var count = context.count // 聚合中点的总数
  var marker = context.marker // 聚合绘制点 Marker 对象
  var color = ['8,60,156', '66,130,198', '107,174,214', '78,200,211']
  var indexs = ['city', 'district', 'area', 'community']
  var i = indexs.indexOf(index['mainKey'])
  var text = clusterData[0][index['mainKey']]
  var size = Math.round(30 + Math.pow(count / points.length, 1 / 5) * 70)
  if (i <= 2) {
    var extra = '<span class="showCount">' + context.count + '套</span>'
    text = '<span class="showName">' + text + '</span>'
    text += extra
  } else {
    size = 12 * text.length + 20
  }
  var style = {
    bgColor: 'rgba(' + color[i] + ',.8)',
    borderColor: 'rgba(' + color[i] + ',1)',
    text: text,
    size: size,
    index: i,
    color: '#ffffff',
    textAlign: 'center',
    boxShadow: '0px 0px 5px rgba(0,0,0,0.8)'
  }
  return style
}
function getPosition(context) {
  var key = context.index.mainKey
  var dataItem = context.clusterData && context.clusterData[0]
  var districtName = dataItem[key]
  if (!district[districtName]) {
    return null
  }
  var center = district[districtName].center.split(',')
  var centerLnglat = new AMap.LngLat(center[0], center[1])
  return centerLnglat
}

// 自定义聚合点样式
function _renderClusterMarker(context) {
  console.log(context)
  var clusterData = context.clusterData // 聚合中包含数据
  var index = context.index // 聚合的条件
  var count = context.count // 聚合中点的总数
  var marker = context.marker // 聚合点标记对象
  var styleObj = getStyle(context)
  // 自定义点标记样式
  var div = document.createElement('div')
  div.className = 'amap-cluster'
  div.style.backgroundColor = styleObj.bgColor
  div.style.width = styleObj.size + 'px'

  if (styleObj.index <= 2) {
    div.style.height = styleObj.size + 'px'
    // 自定义点击事件
    context.marker.on('click', function (e) {
      console.log(e)
      // https://blog.csdn.net/qq_40772640/article/details/127983558
      // 此处逻辑是不调用autofit elRectification的修复索引点击错位问题
      // 但是仍然没有做到完美适配，只做了错位修复，同时也做了地图字体太小问题
      // 但是没有做缩放修复，使用鼠标滚动缩放仍然会发生中心点错位问题
      // 具体是使用这种方式还是使用elRectification的方式，看取舍吧，
      // 如果使用elRectification的方式，点击错位和缩放中心点错位问题都解决了，
      // 但是地图字体太小

      const bodyTransform = document.body.style.transform

      let currentScale = 1
      if (bodyTransform?.includes('scale')) {
        currentScale = bodyTransform.charAt(6)
      }

      const { x, y } = e.pixel

      const pixel2 = new AMap.Pixel(x / currentScale, y / currentScale)

      const { lng, lat } = map.value.containerToLngLat(pixel2)
      // map.value.setZoomAndCenter(curZoom, new AMap.LngLat(lng, lat))

      var curZoom = map.value.getZoom()
      if (curZoom < 20) {
        curZoom += 3
      }
      map.value.setZoomAndCenter(curZoom, e.lnglat)
      // map.value.setZoomAndCenter(curZoom, new AMap.LngLat(lng, lat))
    })
  }
  div.style.border = 'solid 1px ' + styleObj.borderColor
  div.style.borderRadius = styleObj.size + 'px'
  div.innerHTML = styleObj.text
  div.style.color = styleObj.color
  div.style.textAlign = styleObj.textAlign
  div.style.boxShadow = styleObj.boxShadow
  context.marker.setContent(div)
  // 自定义聚合点标记显示位置
  var position = getPosition(context)
  if (position) {
    context.marker.setPosition(position)
  }
  context.marker.setAnchor('center')
}

const map = ref(null)
const cluster = ref(null)

// 初始化地图
const initMap = async () => {
  window._AMapSecurityConfig = {
    securityJsCode: 'a57bb63d1bab0fabcab469adba9f426c'
  }

  const AMap = await AMapLoader.load({
    key: '53ed0523f35af95f296ce0c5b360d960',
    version: '2.0',
    plugins: ['AMap.IndexCluster'],
    zooms: [16, 22]
  })

  // 修复大屏缩放适配后，地图事件偏移问题
  elRectification('.mapContainer', true, 1)

  const bodyTransform = document.body.style.transform

  let currentScale = 1
  if (bodyTransform?.includes('scale')) {
    currentScale = parseFloat(bodyTransform.match(/scale\((.*?)\)/)[1])
  }

  console.log(currentScale)

  const mapBox2 = document.getElementById('mapBox2')
  const width = mapBox2.clientWidth
  const height = mapBox2.clientHeight
  // const width = mapBox2.scrollWidth
  // const height = mapBox2.scrollHeight

  // console.log(width, height)

  // document.getElementById('mapBox2').style.width = `${width * currentScale}px`
  // document.getElementById('mapBox2').style.height = `${height * currentScale}px`
  // document.getElementById('mapBox2').style.transformOrigin = `left top`

  // document.getElementById('mapContainer').style.transform = `scale(${1 / currentScale})`

  map.value = new AMap.Map('mapContainer', {
    zoom: 5,
    // center: [109.034609, 34.34058],
    animateEnable: true,
    mapStyle: 'amap://styles/grey',
    zooms: [3, 22]
  })

  // 创建聚合实例
  cluster.value = new AMap.IndexCluster(map.value, points, {
    renderClusterMarker: _renderClusterMarker,
    clusterIndexSet: clusterIndexSet
  })
}

onMounted(() => {
  initMap()
})

onBeforeUnmount(() => {
  if (map.value) {
    map.value.destroy()
  }
})
</script>

<style scoped>
.mapWrapper {
  width: 100%;
  height: 100%;
  position: relative;
}
.mapContainer {
  width: 100%;
  height: 100%;
  position: relative;
}

:deep(.amap-cluster) {
  display: flex;
  justify-content: center;
  flex-direction: column;
  align-items: center;
  font-size: 12px;
}
:deep(.showName) {
  font-size: 14px;
}
:deep(.showCount),
:deep(.showName) {
  display: block;
  text-overflow: ellipsis;
  white-space: nowrap;
  overflow: hidden;
  width: 80%;
}
</style>
